//
//  FQWebCanGobackAction.m
//  KDFDApp
//
//  Created by Bruce on 2017/11/22.
//  Copyright © 2017年 cailiang. All rights reserved.
//

#import "FQWebCanGobackAction.h"
#import "FQWKWebResponseEntity.h"
#import "FQBaseWKWebViewEntity.h"

@interface FQWebCanGobackAction ()
@property (nonatomic, strong) NSMutableDictionary <NSString *, void(^)(FQWKWebResponseEntity *)>*map;
@property (nonatomic, strong) QCWKWebViewJSRequestEntity *entity;
@property (nonatomic, weak) WKWebView *webView;
@end

@implementation FQWebCanGobackAction
-(NSDictionary<NSString *,void (^)(FQWKWebResponseEntity *)> *)map
{
    if (!_map) {
        _map = [@{} mutableCopy];
    }
    return _map;
}
- (void)setWebView:(WKWebView *)webview
{
    _webView = webview;
}
-(void)action:(QCWKWebViewJSRequestEntity *)requestEntity andCallbackBlock:(void (^)(FQWKWebResponseEntity *))response
{
    _entity = requestEntity;
    if (requestEntity&&requestEntity.callback) {
        [self.map setObject:[response copy] forKey:requestEntity.callback];
    }
    [self canGoback:requestEntity];
}

- (void)canGoback:(QCWKWebViewJSRequestEntity *)request{
    if (_webView) {
         [self successResponseWithRequest:request param:@{@"canGoBack":[_webView canGoBack] ? @1 : @0}];
    }else{
        [self failResponseWithRequest:request];
    }
   
}
-(void)successResponseWithRequest:(QCWKWebViewJSRequestEntity *)request param:(NSDictionary *)param{
    FQWKWebResponseEntity *response = [FQWKWebResponseEntity getResponse];
    response.callbackid = request.callback;
    response.data.code = ENUM_Succeed;
    response.data.message = @"succeed";
    response.data.data = param ? : @{};
    [self.map enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, void (^ _Nonnull obj)(FQWKWebResponseEntity *response), BOOL * _Nonnull stop) {
        if (key == request.callback) {
            obj(response);
        }
    }];
}
-(void)failResponseWithRequest:(QCWKWebViewJSRequestEntity *)request{
    FQWKWebResponseEntity *response = [FQWKWebResponseEntity getResponse];
    response.callbackid = request.callback;
    response.data.code = ENUM_ParamError;
    response.data.message = @"未获取到当前webview";
    response.data.data = @{};
    [self.map enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, void (^ _Nonnull obj)(FQWKWebResponseEntity *response), BOOL * _Nonnull stop) {
        if (key == request.callback) {
            obj(response);
        }
    }];
}
@end
